﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Entity;

namespace UDS.WebApp.SubModule
{
    public partial class AddUpdateCatalogPage : Page
    {
        protected CatalogInfo CurrentCatalog
        {
            get;
            private set;
        }

        protected override void OnInit(EventArgs e)
        {
            int catalogId = QSUtil.GetPositiveInt32("CatalogID");
            if (catalogId > 0)
            {
                foreach (var catalog in CommonFile.GetCatalogs())
                {
                    if (catalog.CatalogID == catalogId)
                    {
                        CurrentCatalog = catalog;
                        break;
                    }
                }
            }

            lblTitle.Text = (CurrentCatalog == null) ? "新增分类" : "编辑分类";
            if (CurrentCatalog != null)
            {
                txtName.Text = CurrentCatalog.Catalog;
            }

            // Hook event handler
            btnAddUpdate.Click += new EventHandler(OnAddUpdate_Click);
            base.OnInit(e);
        }

        private void OnAddUpdate_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                CatalogInfo catalog = CurrentCatalog;
                if (catalog == null)
                {
                    catalog = new CatalogInfo();
                    catalog.CatalogID = -1; // To create a new catalog.
                }
                catalog.Catalog = txtName.Text;
                catalog.Creator = SiteContext.Current.UserName;

                try
                {
                    CommonFile.AddUpdateCatalog(catalog);
                    Response.Redirect("Catalog.aspx");
                }
                catch (Exception ex)
                {
                    SiteContext.Current.AlertException("没有成功更新/新建分类", ex);
                }
            }
        }
    }
}
